package com.bankfourfactor;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.seek.cache.CacheUtil;
import com.seek.common.handler.SpringContextHolder;
import com.seek.inter.interdto.InterDtoCUser;
import com.seek.model.dto.ResultInfo;
import com.seek.model.entity.TBaseBanktype;
import com.seek.model.entity.TBizFlow;
import com.seek.model.entity.TCustomerCard;
import com.seek.service.BizFlowService;
import com.seek.service.CustomerCardService;
import com.seek.util.BankNameUtil;
import com.seek.util.BankUtil;
import com.seek.util.CommonUtil;
import com.seek.util.DateUtil;

public class APPBankCarFactor {
	private Logger logger = LoggerFactory.getLogger(APPBankCarFactor.class);
	
	private  CustomerCardService  customerCardService =  (CustomerCardService)SpringContextHolder.getBean("customerCardService");
	private  BizFlowService  bizFlowService =  (BizFlowService)SpringContextHolder.getBean("bizFlowService");
	
	/**
	 * carName：户名
	 * carNO：户号
	 * idNo：身份证号
	 * mobile：电话号
	 * @throws Exception 
	 * **/
	public  ResultInfo submitFourFactor(HttpServletRequest request, com.alibaba.fastjson.JSONObject reqJson) throws Exception{
		String cardNo = reqJson.getString("cardNo");//银行卡号
		String mobile = reqJson.getString("mobile");//电话号码，缓存里存在，但是我还是觉得应该传递一边，因为一个人不同的手机，但是和关联的身份证，银行卡送去认证，应该是会成功的
		String companyId = reqJson.getString("companyId");//商户ID
		String token = reqJson.getString("token");
		InterDtoCUser cust = com.seek.cache.CacheUtil.getCLoginCache(token);
		ResultInfo result = new ResultInfo();
		ResParam param = new ResParam();
		//判断传递的参数是否有缺失,银行卡号和缓存里面银行卡号是否一致,手机号码是否和缓存中是否一致,校验
		if(StringUtils.isNotBlank(cardNo)&&StringUtils.isNotBlank(mobile)&&mobile.equals(cust.getPhoneNo())&&StringUtils.isNotBlank(cust.getCustId())){
			if(!BankUtil.checkBankCard(cardNo)){
				result.setStatus(1);
				result.setMessage("银行卡号有误，请检查");
				param.setCode("3");
				param.setMessage("银行卡号有误，请检查");
				result.setBody(param);
				return result;
			}
			String cardDetail = CacheUtil.getRedisData("CARD_AUTH_" + cust.getCustId());
			if(StringUtils.isNotEmpty(cardDetail) && StringUtils.equals(cardNo,cardDetail)){
				result.setStatus(1);
				result.setMessage("操作过快，请30秒后再试");
				return result;
			}

			CacheUtil.putRedisDataEx("CARD_AUTH_" + cust.getCustId(),cardNo,30L);

			//根据银行卡名称，身份证号，户名，手机号进行查询是否认证过(防止相同信息重复认证，消耗认证金额)
			String sql = "select audit_status auditStatus,card_number cardNumber,"
					   + "bank_phone bankPhone,DATE_FORMAT(submit_time,'%Y-%m-%d') submitTime,audit_remark auditRemark,bank_name bankName from t_customer_card where customer_id=? and history = ?";
			Map<String,Object> map = customerCardService.findOneMapBySql(sql,new Object[]{CommonUtil.getLongValue(cust.getCustId()),0});
			Map<String,Object> businessMap  = new HashMap<String, Object>();
			//认证过
			if(MapUtils.isNotEmpty(map)){
				//信息一致，但是状态不是未审核状态的时候
				if(cardNo.equals(map.get("cardNumber"))&&mobile.equals(map.get("bankPhone"))&&StringUtils.isNotBlank(map.get("auditStatus")+"")&&!StringUtils.equals(map.get("auditStatus")+"","0")){
					result.setStatus(0);
					result.setMessage("该银行卡已认证，认证结果为："+((map.get("auditStatus")+"").equals("1")?"认证通过":"认证失败"));
					if(StringUtils.equals(map.get("auditStatus")+"", "1")){
						String cardNumber = cust.getCardNumber();
						param.setCardNo("**** **** **** "+StringUtils.substring(cardNumber,cardNumber.length()-4));
						TBaseBanktype baseBankType = CacheUtil.getTBaseBanktype(BankNameUtil.getBankName(map.get("bankName")+""));
						if(null!=baseBankType){
							param.setLogoUrl(baseBankType.getTypeLogo());
						}
						param.setBankName(cust.getBankName());
					}
					String submitTime = (String)map.get("submitTime");
					param.setSubmitTime(StringUtils.isNotEmpty(submitTime) ? submitTime :"");
					param.setCode(cust.getCardBindStatus());
					param.setMessage(map.get("auditRemark")+"");
					result.setBody(param);
					return result;
				}
				businessMap.put("type", "update");
			}
			
			BankCarFactorEntity banCardfactor = new BankCarFactorEntity();
			logger.info("===========error记录少，容易查找============================没进行UTF-8转换的cust.getCustName()"+cust.getCustName()+"==============进行UTF-8转换后的cust.getCustName()========================="+new String(cust.getCustName().getBytes(),"UTF-8"));
			banCardfactor.setCardName(new String(cust.getCustName().getBytes(),"UTF-8"));
			banCardfactor.setCardNo(cardNo);
			logger.info("================error记录少，容易查找=======================没进行UTF-8转换的cust.getCustName()"+cust.getCustName()+"==============进行UTF-8转换后的cust.getCustName()========================="+new String(cust.getCustName().getBytes(),"UTF-8"));
			banCardfactor.setIdName(new String(cust.getCustName().getBytes(),"UTF-8"));
			banCardfactor.setIdNo(cust.getCustNumber());
			banCardfactor.setPhone(mobile);
			banCardfactor.setSeq(System.currentTimeMillis()+""+cust.getCustId());
			banCardfactor.setCustId(cust.getCustId());
			banCardfactor.setCompanyId(companyId);
			banCardfactor.setBankName(BankUtil.getNameOfBank(cardNo));
			//调用第三方接口的记录
			TBizFlow bizFlow = new TBizFlow();
			bizFlow.setCompanyId(CommonUtil.getLongValue(companyId));
			bizFlow.setCustomerId(CommonUtil.getLongValue(cust.getCustId()));
			bizFlow.setBizNo(banCardfactor.getSeq());
			bizFlow.setBizType("银行4要素认证");
			bizFlow.setOrgCode("");
			bizFlow.setDeleted(0);
			bizFlow.setOrgBizNo("");
			bizFlow.setStatus("");
			bizFlow.setCreateTime(new Date());
			bizFlow.setModifyTime(new Date());
			tbizflowHelp(bizFlow);//添加流水
			
			//银行卡表的实体类
			TCustomerCard  tcustomerCard = new TCustomerCard();
			tcustomerCard.setCompanyId(new Long(companyId));
			tcustomerCard.setCustomerId(CommonUtil.getLongValue(cust.getCustId()));
			tcustomerCard.setBankName("");
			tcustomerCard.setCardNumber(cardNo);
			tcustomerCard.setBankPhone(mobile);
			tcustomerCard.setSubmitTime(new Date());
			tcustomerCard.setAuditStatus(0);
			tcustomerCard.setHistory(0);
			
			//对数据进行封装，传入service进行业务处理
			businessMap.put("tcustomerCard", tcustomerCard);
			businessMap.put("bizFlow", bizFlow);
			businessMap.put("banCardfactor", banCardfactor);
			//有过认证数据，需要对认证数据进行修改，把他置成历史数据，并进行接口调用，和业务逻辑处理
			customerCardService.addBankBind(businessMap);
			
			//接口调用记录表添加完毕之后，进行接口调用
			BankFourFactor  bankFourFactor = new BankFourFactor(); 
			result = bankFourFactor.submitYouDunFactor(banCardfactor);
		}else{
			result.setStatus(1);
			result.setMessage("参数有误，请检查");
			param.setCode("3");
			param.setMessage("参数有误，请检查");
			result.setBody(param);
			
		}
		return result;
	} 
	
	
	
	
	
	
	
	
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void tbizflowHelp(TBizFlow bizFlow){
		try {
			bizFlowService.save(bizFlow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
